iT邦幫忙

2025 iThome 鐵人賽

DAY 3
2
Software Development

30 天 Effective C++ 大挑戰!!系列 第 3

[Day 3] Constructors, Destructors, and Assignment Operators I

  • 分享至 

  • xImage
  •  

本篇開始進入《Effective C++》的第二個章節,其中涵蓋的知識點皆彼此相關,內容更具有挑戰性及啟發性。歡迎和 Yoyo 一起探索建構子的世界!

5. Know what functions C++ silently writes and calls

當 class 被調用時,C++ 編譯器會自動建立 4 個 member function,且均預設為 public。以下將簡單敘述各項目的呼叫時機。

  • default constructor (non-virtual):創建一個 object 且未提供任何初始化參數。
  • copy constructor:用現有的 object 建立初始化另一個同型別的 object。
  • copy assigment operator:當已存在的 object 被賦值為另一個同型別的 object。
  • destructor:當 object 的生命週期結束時用以清除資源。 e.g. 釋放記憶體、關閉檔案

若有使用 new 等方式動態配置記憶體,則應自行定義 destructor、copy constructor、copy assignment operator,以避免 shallow copy 造成的資源錯誤。

6. Explicitly disallow the use of compiler-generated functions you do not want

若想禁用自動產生的 function,有以下 2 種方法:

  • 將此 member function 放到 private 並宣告為 delete。若為 C++ 11 以前的版本則可用 iostreams 標準程式函式庫進行實作。
  • 將此 class 「繼承」自一個無法複製的 base class。這樣做會將 copy constructor 與 copy assignment operator 皆設為 private

7. Declare destructors virtual in polymorphic base classes

「多型」是指在物件導向程式設計中,可以透過指向 base class 的指標或參考來操作 derived class 的能力。這樣的特性支援啟用虛擬調用,在執行期才依據 object 的實際型別判斷該呼叫的 member function,而非在編譯期間就決定。

在 C++ 中,若 class 至少有一個 virtual 函數,就會被視為多型類別。必須定義 virtual destructor,以確保透過 base class 指標刪除物件時能正確釋放資源。

8. Prevent exceptions from leaving destructors

如同第 5 點所提到的,destructor 會清除 object 的資源。想像一下若過程出現異常,destructor 在丟出 exception 後依舊持續清理,最終 exception 只會堆積成山。C++ 對於這種未定義行為,可能會出現預期之外的錯誤。

那為了避免這種情形,該如何設計 class 呢?

  • try ... catch 紀錄錯誤並終止程式。
  • 使用 interface 讓客戶端有機會對可能出現的問題做出反應。
class DBConn{
public:
    void close() {
        db.close();
        closed = true;
    }
    ~DBConn() {
        if(!closed){
            try {
                db.close();
            } catch (...) {
                // log of abort
            }
        }
    }
private:
    DBConnetion db;
    bool closed;
}

上一篇
[Day 2] Accustoming Yourself to C++
下一篇
[Day 4] Constructors, Destructors, and Assignment Operators II
系列文
30 天 Effective C++ 大挑戰!!30
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言